package org.example.thread.semaphore;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Classname SemaphoreTest
 * @Description TODO
 * @Date 2021/4/21 10:13 上午
 * @Created by xiangjd
 */
public class SemaphoreTest {

   private  static Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //线程排队
                String name = Thread.currentThread().getName();
                System.out.println(String.format("老司机: %s,在停车场外排队,当前时间为: %s", name, new Date()));
                try {
                    Thread.sleep(100);
                    //获取锁并阻塞其他现车鞥
                    semaphore.acquire();
                    System.out.println(String.format("老司机: %s,已经进入停车场,当前时间为:%s", name, new Date()));
                    Thread.sleep(1000);
                    System.out.println(String.format("老司机: %s,从停车场出来,当前时间为: %s", name, new Date()));
                    //释放锁
                    semaphore.release();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        executorService.submit(runnable);
        executorService.submit(runnable);
        executorService.submit(runnable);
        executorService.submit(runnable);
        executorService.submit(runnable);
        executorService.shutdown();
    }
}
